package com.app.server;

import java.sql.Connection;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import redis.clients.jedis.Jedis;

import com.app.db.DaoUtil;
import com.app.store.AbstractMySqlStore;

public class DelQueueRunnable extends QueueRunnable {

	DelQueueRunnable(String tableName,AbstractMySqlStore store,ScheduledExecutorService service) {
		super(tableName,store,store.genDelQueueKey(tableName),service);
	}

	@Override
	public void run() {
		Connection conn = null;
		String delKey = null;
		Jedis jedis = null;
		
		try {
			jedis = client.getJedis();
			conn = pool.getConnection();
			while (!stop && (delKey = jedis.spop(queueKey)) != null) {
				try {
					store.delFromDelQueue(tableName, Long.parseLong(delKey), conn);
					errorTimes = 0;
					if(logger.isDebugEnabled()) {
						logger.debug("del---------"+delKey);
					}
				} catch (Exception e) {
					errorTimes ++;
					e.printStackTrace();
					logger.error(e.getMessage() + " delQueue tableName:" + tableName, e);
					if(delKey != null) {
						jedis.sadd(queueKey, delKey);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage() + " delQueue tableName:" + tableName, e);
			errorTimes ++;
			if(errorTimes > 10) {
				logger.error(queueKey+" errorTimes:"+errorTimes);
			}
		} finally {
			DaoUtil.close(conn);
			conn = null;
			client.returnJedis(jedis);
			jedis = null;
			if(!stop) {
				service.schedule(this, UPDATE_INTERVAL, TimeUnit.SECONDS);
			}
			else {
				done = true;
				logger.info(queueKey+" is done......");
			}
		}
		
	}
}